package cn.zl.web.dto;

import cn.hutool.core.util.StrUtil;
import cn.yunbamboos.rest.service.dto.Data;
import cn.yunbamboos.rest.service.dto.out.GenericOutDTO;
import cn.zl.config.ZLConfig;

import java.util.HashMap;
import java.util.Map;

public class PlayStreamOutDTO extends GenericOutDTO {

    private String host;
    private String app;
    private String stream;
    private ZLConfig config;

    @Override
    public void encode(Data data) {
        super.encode(data);
        String ip = getIp();
        Map<String, String> templates = config.getPlayUrlTemplate();
        for (Map.Entry<String, String> entry : templates.entrySet()) {
            String key = entry.getKey();
            String template = entry.getValue();
            data.set(key, url(template, ip, config.getZLMPort(key)));
        }
    }

    private String url(String template, String ip, int port) {
        Map<String, String> param = new HashMap<>();
        param.put("ip", ip);
        param.put("port", String.valueOf(port));
        param.put("app", app);
        param.put("stream", stream);
        return StrUtil.format(template, param);
    }

    private String getIp() {
        if ("localhost".equals(host) || "127.0.0.1".equals(host)) {
            return host;
        }
        String ips = config.getIp();
        if (ips.contains(host)) {
            return host;
        }
        return ips.split(",")[0];
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setApp(String app) {
        this.app = app;
    }

    public void setStream(String stream) {
        this.stream = stream;
    }

    public void setConfig(ZLConfig config) {
        this.config = config;
    }
}
